package com.ruoyi.eims.store.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.base.api.AccountService;
import com.ruoyi.base.api.InventoryService;
import com.ruoyi.base.api.domain.Account;
import com.ruoyi.base.api.domain.InvVo;
import com.ruoyi.base.api.domain.Inventory;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.eims.purchase.domain.PurchaseOrder;
import com.ruoyi.eims.purchase.domain.PurchaseOrderDetails;
import com.ruoyi.eims.purchase.domain.PurchasePay;
import com.ruoyi.eims.purchase.mapper.PurchaseOrderDetailsMapper;
import com.ruoyi.eims.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.eims.store.domain.InboundOrderDetails;
import com.ruoyi.eims.store.domain.InboundPay;
import com.ruoyi.eims.store.dto.InBoundDto;
import com.ruoyi.eims.store.mapper.InboundOrderDetailsMapper;
import com.ruoyi.eims.store.mapper.InboundPayMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.eims.store.mapper.InboundOrderMapper;
import com.ruoyi.eims.store.domain.InboundOrder;
import com.ruoyi.eims.store.service.IInboundOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购入库管理Service业务层处理
 * 
 * @author hp
 * @date 2023-02-05
 */
@Service
public class InboundOrderServiceImpl implements IInboundOrderService 
{
    @Autowired
    private InboundOrderMapper inboundOrderMapper;
    @Autowired
    private InboundOrderDetailsMapper inboundOrderDetailsMapper;
    @Autowired
    private AccountService accountService;
    @Autowired
    private InboundPayMapper inboundPayMapper;
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private PurchaseOrderDetailsMapper purchaseOrderDetailsMapper;

    /**
     * 查询采购入库管理
     * 
     * @param id 采购入库管理主键
     * @return 采购入库管理
     */
    @Override
    public InboundOrder selectInboundOrderById(Long id)
    {
        return inboundOrderMapper.selectInboundOrderById(id);
    }

    /**
     * 查询采购入库管理列表
     * 
     * @param inboundOrder 采购入库管理
     * @return 采购入库管理
     */
    @Override
    public List<InboundOrder> selectInboundOrderList(InboundOrder inboundOrder)
    {
        return inboundOrderMapper.selectInboundOrderList(inboundOrder);
    }

    /**
     * 新增采购入库管理
     * 
     * @param inBoundDto 采购入库管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertInboundOrder(InBoundDto inBoundDto)
    {
        if (inBoundDto.getWarehouseId() == null) {
            throw new RuntimeException("仓库不能为空");
        }

        List<PurchaseOrder> list = inBoundDto.getSelectCgorderList();
        String collect = list.stream().map(PurchaseOrder::getGoodsId).collect(Collectors.joining(","));
        String goodsId = String.join(",", Arrays.stream(collect.split(",")).collect(Collectors.toSet()));

        InboundOrder order = new InboundOrder();
        order.setCreateDate(new Date());
        //order.setGoodsId();
        order.setHasPay(inBoundDto.getPayamount());
        order.setOrderNo(list.stream().map(PurchaseOrder::getOrderNo).collect(Collectors.joining(",")));
        //order.setPid();
        order.setPrice(inBoundDto.getTotalAmount().subtract(inBoundDto.getDepositAmount()).subtract(inBoundDto.getDiscountAmount()));
        order.setShouldPay(order.getPrice().subtract(inBoundDto.getPayamount()));
        order.setGoodsId(goodsId);
        order.setState(inBoundDto.getState());
        order.setUserId(SecurityUtils.getUserId());
        order.setVendorId(list.stream().map(t->String.valueOf(t.getVendorId())).distinct().collect(Collectors.joining(",")));
        order.setVendorName(String.join(",", Arrays.stream(inBoundDto.getVendorName()).collect(Collectors.toSet())));

        int i = inboundOrderMapper.insertInboundOrder(order);

        InboundOrderDetails details = new InboundOrderDetails();
        details.setAccountId(inBoundDto.getAccountId());
        details.setCountPrice(inBoundDto.getTotalAmount());
        details.setDebt(inBoundDto.getDebtAmount());
        details.setDesPrice(inBoundDto.getDepositAmount());
        details.setOrderId(order.getId());
        details.setPayPrice(inBoundDto.getPayamount());
        details.setPreferentialPrice(inBoundDto.getDiscountAmount());
        BigDecimal subtract = inBoundDto.getTotalAmount().subtract(inBoundDto.getDepositAmount()).subtract(inBoundDto.getDiscountAmount());
        details.setRealPrice(subtract);
        details.setWarehouseId(inBoundDto.getWarehouseId());

        inboundOrderDetailsMapper.insertInboundOrderDetails(details);

        //审核通过账号扣钱
        /*if (inBoundDto.getState() == 1) {
            AjaxResult result = accountService.getInfo(inBoundDto.getAccountId());

            Object o = result.get(AjaxResult.DATA_TAG);
            String s = JSONObject.toJSONString(o);
            Account account = JSONObject.parseObject(s, Account.class);

            account.setCurrentBalance(account.getCurrentBalance().subtract(inBoundDto.getPayamount()));
            accountService.edit(account);

            //生成订单
            InboundPay pay = new InboundPay();
            pay.setAccountId(inBoundDto.getAccountId());
            pay.setCreatedate(new Date());
            pay.setInboundOrderId(order.getId());
            pay.setNote("入库支付单");
            pay.setPrice(inBoundDto.getPayamount());
            pay.setOrderno(order.getOrderNo());
            inboundPayMapper.insertInboundPay(pay);

            //加库存
            String orderNos = order.getOrderNo();
            String[] split = orderNos.split(",");
            Inventory inventory = new Inventory();
            for (String orderNo : Arrays.stream(split).collect(Collectors.toList())) {
                PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderByOrderNo(orderNo);
                List<PurchaseOrderDetails>  purchaseOrderDetails = purchaseOrderDetailsMapper.selectPurchaseOrderDetailsByOrderId(purchaseOrder.getId());

                for (PurchaseOrderDetails detail : purchaseOrderDetails) {
                    inventory.setWarehouseId(inBoundDto.getWarehouseId());
                    //inventory.setCategory();
                    inventory.setGoodsId(detail.getGoodsId());
                    inventory.setInventory(String.valueOf(detail.getCount()));
                    inventory.setPrice(detail.getPrice());
                    inventory.setState(0);
                    inventoryService.save(inventory);
                }

            }
        }*/

        if (inBoundDto.getState() == 1) {
            shenghe(order);
        }




        //System.out.println(order);
        //return inboundOrderMapper.insertInboundOrder(inBoundDto);
        return i;
    }

    /**
     * 修改采购入库管理
     * 
     * @param inboundOrder 采购入库管理
     * @return 结果
     */
    @Override
    public int updateInboundOrder(InboundOrder inboundOrder)
    {
        return inboundOrderMapper.updateInboundOrder(inboundOrder);
    }

    /**
     * 批量删除采购入库管理
     * 
     * @param ids 需要删除的采购入库管理主键
     * @return 结果
     */
    @Override
    public int deleteInboundOrderByIds(Long[] ids)
    {
        return inboundOrderMapper.deleteInboundOrderByIds(ids);
    }

    /**
     * 删除采购入库管理信息
     * 
     * @param id 采购入库管理主键
     * @return 结果
     */
    @Override
    public int deleteInboundOrderById(Long id)
    {
        return inboundOrderMapper.deleteInboundOrderById(id);
    }

    @Override
    @Transactional
    public int shenghe(InboundOrder inboundOrder) {

        inboundOrder.setState(1);

        InboundOrderDetails details = inboundOrderDetailsMapper.selectInboundOrderDetailsByOrderId(inboundOrder.getId());

        AjaxResult result = accountService.getInfo(details.getAccountId());

        Object o = result.get(AjaxResult.DATA_TAG);
        String s = JSONObject.toJSONString(o);
        Account account = JSONObject.parseObject(s, Account.class);

        account.setCurrentBalance(account.getCurrentBalance().subtract(details.getPayPrice()));
        accountService.edit(account);

        //生成订单
        InboundPay pay = new InboundPay();
        pay.setAccountId(details.getAccountId());
        pay.setCreatedate(new Date());
        pay.setInboundOrderId(inboundOrder.getId());
        pay.setNote("入库支付单");
        pay.setPrice(details.getPayPrice());
        pay.setOrderno(inboundOrder.getOrderNo());
        inboundPayMapper.insertInboundPay(pay);

        //加库存
        String orderNos = inboundOrder.getOrderNo();
        String[] split = orderNos.split(",");
        Inventory inventory = new Inventory();
        for (String orderNo : Arrays.stream(split).collect(Collectors.toList())) {
            PurchaseOrder purchaseOrder = purchaseOrderMapper.selectPurchaseOrderByOrderNo(orderNo);
            purchaseOrder.setState(2);
            List<PurchaseOrderDetails>  purchaseOrderDetails = purchaseOrderDetailsMapper.selectPurchaseOrderDetailsByOrderId(purchaseOrder.getId());

            for (PurchaseOrderDetails detail : purchaseOrderDetails) {
                inventory.setWarehouseId(details.getWarehouseId());
                //inventory.setCategory();
                inventory.setGoodsId(detail.getGoodsId());
                inventory.setInventory(String.valueOf(detail.getCount()));
                inventory.setPrice(detail.getPrice());
                inventory.setState(0);
                inventoryService.save(inventory);
            }
            purchaseOrderMapper.updatePurchaseOrder(purchaseOrder);
        }

        return inboundOrderMapper.updateInboundOrder(inboundOrder);
    }
}
